package org.basis.algorithm.sort;

import org.basis.algorithm.sort.common.SortUtil;

import java.util.Arrays;

/**
 * 冒泡排序
 *
 * @author Mr_wenpan@163.com 2022/01/26 15:43
 */
public class BubbleSort {

    public static void main(String[] args) {
        final int num = 10000;
        // 对数器校验算法的正确性
        for (int i = 0; i < num; i++) {
            int[] ints = SortUtil.generateRandomArray(100, 100);
            int[] copy = SortUtil.copyArray(ints);
            sort(ints);
            Arrays.sort(copy);
            if (!SortUtil.isEqual(copy, ints)) {
                System.out.println("fuck.");
            }
        }
    }

    public static void sort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        // 要进行n轮冒泡
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // 交换
                    swap(arr, j, j + 1);
                }
            }
        }
    }

    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

}
